package com.youfang.sixthmedia;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.gzit.common.async.AsynCallback;
import com.gzit.common.async.LoadingCallback;
import com.gzit.utils.AndroidUtils;
import com.gzit.utils.StringUtils;
import com.youfang.sixthmedia.calc.CalcActivity;
import com.youfang.sixthmedia.chat.service.BuddyMessageService;
import com.youfang.sixthmedia.chat.service.UNReadMessageMonitorService;
import com.youfang.sixthmedia.common.YoufangContext;
import com.youfang.sixthmedia.message.LoginRequest;
import com.youfang.sixthmedia.message.LoginResponse;
import com.youfang.sixthmedia.message.model.User;
import com.youfang.sixthmedia.net.Net;
import com.youfang.sixthmedia.net.Response;
import com.youfang.sixthmedia.ui.center.TabCenterActivity;
import com.youfang.sixthmedia.ui.searcher.SearcherResultActivity;

/**
 * 主屏
 * 
 * @author teddy
 * 
 */
public class MainActivity extends Activity {

	int[] ids = new int[] { R.id.newbtn, R.id.searcherbtn, R.id.nearbybtn,
			R.id.tuanggoubtn, R.id.discountbtn, R.id.friendbtn, R.id.centerbtn,
			R.id.calcbtn, R.id.settingbtn };

	OnClickListener listener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			switch (v.getId()) {
			case R.id.newbtn:
				gotoTabActivity(0);
				break;
			case R.id.searcherbtn:
				gotoTabActivity(1);
				break;

			case R.id.discountbtn:
				gotoTabActivity(2);
				break;
			case R.id.tuanggoubtn:
				gotoTabActivity(3);
				break;
			case R.id.nearbybtn:
				gotoNearByBuildingActivity();
				break;
			case R.id.friendbtn:
				gotoNearByBuddyActivity();
				break;
			case R.id.centerbtn:
				if (YoufangContext.getUser() == null) {
					gotoLoginActivity();
					return;

				}
				gotoCenterActivity();
				break;
			case R.id.calcbtn:
				gotoCalcActivity();

				break;
			case R.id.settingbtn:
				gotoSettingActivity();
				break;

			case R.id.login_out_btn:

				// user not logined,goto login activity
				if (YoufangContext.getUser() == null) {
					gotoLoginActivity();
					return;

				}

				// user logined,do logout
				logout();
				break;

			// search button in the main screen
			case R.id.searchbtn:
				gotoSearchResultActivity();

				break;

			// 进入城市选择
			case R.id.cityName:
			case R.id.cityArrow:
				gotoCityActivity();
				break;

			}

		}
	};

	private void gotoSettingActivity() {
		Intent intent = new Intent();
		intent.setClass(this, SettingActivity.class);
		this.startActivity(intent);

	}

	private void gotoCalcActivity() {
		Intent intent = new Intent();
		intent.setClass(this, CalcActivity.class);
		this.startActivity(intent);

	}

	private void gotoSearchResultActivity() {
		String content = ((EditText) this.findViewById(R.id.keyword)).getText()
				.toString();
		if (StringUtils.isBlank(content)) {
			AndroidUtils.toastShort("请输入要搜索的楼盘地址和楼盘名...");
			return;
		}

		YoufangContext.resetSearcherFilter(content);

		Intent intent = new Intent();
		intent.setClass(this, SearcherResultActivity.class);
		this.startActivity(intent);

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AndroidUtils.Screen.noWindowTitle(this);
		this.setContentView(R.layout.main_activity);
		for (int id : ids) {
			this.findViewById(id).setOnClickListener(listener);
		}

		for (int id : new int[] { R.id.login_out_btn, R.id.cityName,
				R.id.cityArrow, R.id.searchbtn }) {
			this.findViewById(id).setOnClickListener(listener);
		}

		// try to do auto login...
		tryRemoteLogin();

		// start services...
		BuddyMessageService.start(this);
		UNReadMessageMonitorService.start(this);
	}

	private void logout() {

		AndroidUtils.Dialog.confirm(MainActivity.this, "提示", "是否注销登录?",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {

						final LoadingCallback loading = new LoadingCallback.DefaultLoadingCallback(
								MainActivity.this);

						// do it in background
						new AsyncTask<String, Integer, Boolean>() {

							@Override
							protected void onPostExecute(Boolean result) {
								super.onPostExecute(result);
								loading.hideLoading();
								updateUserInfoUI();
							}

							@Override
							protected Boolean doInBackground(String... params) {
								YoufangContext.clearUserInfo();
								return true;
							}

							@Override
							protected void onPreExecute() {
								super.onPreExecute();
								loading.showLoading();
							}
						}.execute("");

					}
				});
	}

	private void tryRemoteLogin() {

		final User olduser = YoufangContext.getUser();
		if (olduser == null || StringUtils.isBlank(olduser.username)
				|| StringUtils.isBlank(olduser.password)) {
			return;
		}

		LoginRequest req = new LoginRequest();
		req.setUsername(olduser.username);
		req.setPassword(olduser.password);

		Net.doHttpRemote(this, req, new LoginResponse(),
				new AsynCallback<Response>() {

					@Override
					public void callback(Response r) {
						if (!r.isOk()) {
							YoufangContext.clearUserInfo();
						} else {

							// 登录成功...
							LoginResponse resp = (LoginResponse) r;
							User user = resp.getUser();

							// save user infomation
							user.password = olduser.password;
							YoufangContext.saveUserAndStartMessageService(user);
						}

						updateUserInfoUI();

					}
				});

	}

	@Override
	protected void onResume() {
		super.onResume();

		// city info
		((TextView) this.findViewById(R.id.cityName)).setText(YoufangContext
				.getCity().name + "站");

		updateUserInfoUI();

		regService();
	}

	private void updateUserInfoUI() {
		User user = YoufangContext.getUser();
		String userName = "游客";
		String btnLabel = "登录";
		if (user != null) {
			userName = user.nickname;
			btnLabel = "注销";
		}
		((Button) this.findViewById(R.id.login_out_btn)).setText(btnLabel);
		((TextView) this.findViewById(R.id.name)).setText("您好，" + userName);

		ImageView photo = (ImageView) this.findViewById(R.id.photo);
		Uri uri = YoufangContext.getUserLogo();
		if (uri == null) {
			photo.setImageResource(R.drawable.common_head);
			return;
		}

		photo.setImageURI(uri);

	}

	private void gotoNearByBuildingActivity() {
		Intent intent = new Intent();
		intent.setClass(this, NearByBuildActivity.class);
		this.startActivity(intent);

	}

	private void gotoNearByBuddyActivity() {
		Intent intent = new Intent();
		intent.setClass(this, NearByBuddyActivity.class);
		this.startActivity(intent);

	}

	private void gotoCenterActivity() {
		Intent intent = new Intent();
		intent.setClass(this, TabCenterActivity.class);
		this.startActivity(intent);

	}

	private void gotoLoginActivity() {

		Intent intent = new Intent();
		intent.setClass(this, LoginActivity.class);
		this.startActivityForResult(intent, LOGIN_REQUEST_CODE);

	}

	private void gotoTabActivity(int index) {
		Intent intent = new Intent();
		intent.putExtra("tabIndex", index);
		intent.setClass(this, TabMainActivity.class);
		this.startActivity(intent);

	}

	private void gotoCityActivity() {
		Intent intent = new Intent();
		intent.setClass(this, CityActivity.class);
		this.startActivityForResult(intent, CITY_REQUEST_CODE);
	}

	private static final int LOGIN_REQUEST_CODE = 1;
	private static final int CITY_REQUEST_CODE = 2;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode != Activity.RESULT_OK) {
			return;
		}

		switch (requestCode) {
		case LOGIN_REQUEST_CODE:
			// 登录成功，更新底部状态条
			if (resultCode == Activity.RESULT_OK) {
				// user info
				updateUserInfoUI();
			}
			break;

		case CITY_REQUEST_CODE:
			((TextView) this.findViewById(R.id.cityName))
					.setText(YoufangContext.getCity().name);
			break;
		}

	}

	// ///////////////////
	private BroadcastReceiver messageReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {

			int userid = intent.getIntExtra("userid", 0);
			if (!YoufangContext.isLogined()) {
				return;
			}

			if (userid != YoufangContext.getUser().userid) {
				return;
			}

			int count = intent.getIntExtra("data", 0);
			TextView countView = (TextView) findViewById(R.id.status);
			countView.setVisibility(count == 0 ? View.INVISIBLE : View.VISIBLE);
			countView.setText("" + count);

		}
	};

	private void regService() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(YoufangContext.CHAT_UNREAD_MESSAGE_ATION);
		registerReceiver(messageReceiver, filter);
	}

	@Override
	protected void onPause() {
		super.onPause();
		unregisterReceiver(messageReceiver);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// stop services
		BuddyMessageService.stop(this);
		UNReadMessageMonitorService.stop(this);
	}

}
